package pers.rcl.plugin;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.Prop;
import com.jfinal.plugin.IPlugin;

import pers.rcl.utils.xx;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.*;

public class QuartzPlugin implements IPlugin {

	private SchedulerFactory sf = null;

	public static Scheduler scheduler = null;

	/**
	 * 启动Quartz
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean start() {
		// 创建调度工厂
		sf = new StdSchedulerFactory();

		try {
			scheduler = sf.getScheduler();

			Properties properties = new Prop("quartz-jobs.properties").getProperties();
			Set keyValue = properties.keySet();

			Iterator<String> it = keyValue.iterator();

			List<String> size = new ArrayList<String>();

			while (it.hasNext()) {
				String str = it.next();
				if (!str.trim().isEmpty()) {
					String[] name = str.trim().split("\\.");
					boolean bool = size.contains(name[0]);

					if (!bool) {
						size.add(name[0].trim());
					}
				}
			}

			System.out.println("注册定时任务.................");
			for (int j = 0; j < size.size(); j++) {
				String jobName = properties.getProperty(size.get(j) + ".job");
				String jobCron = properties.getProperty(size.get(j) + ".cron");
				String jobEnable = properties.getProperty(size.get(j) + ".enable");

				// System.out.println("任务详情为：任务名-" + jobName + " 时间：" + jobCron + "是否开启：" +
				// jobEnable);
				if (xx.toBoolean(jobEnable)) {
					openJOb(jobName, jobCron);
				}
			}

		} catch (SchedulerException e) {
			e.printStackTrace();
		}

		return true;

	}

	/**
	 * 
	 * @param jobClassName
	 *            任务类
	 * @param jobCronExp
	 *            cron表达式，任务开启时间
	 * @throws SchedulerException
	 */
	public void openJOb(String jobClassName, String jobCronExp) throws SchedulerException {
		Class clazz;
		try {
			clazz = Class.forName(jobClassName);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}

		JobDetail job = JobBuilder.newJob(clazz).withIdentity(jobClassName, jobClassName).build();
		CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobClassName).withSchedule(CronScheduleBuilder.cronSchedule(jobCronExp)).build();

		try {
			scheduler.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			new RuntimeException(e);
		}

		LogKit.info(job.getKey() + " loading and exp: " + trigger.getCronExpression());

		scheduler.start();
	}

	/**
	 * 停止Quartz
	 */
	@Override
	public boolean stop() {
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			LogKit.error("shutdown error", e);
			return false;
		}
		return true;
	}
}
